package com.leyou.gateway.filters;

import com.leyou.gateway.task.IntervalTokenHolder;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

@Component
public class TokenAddFilter  extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //过滤器执行次序，zuul在请求其他服务时，添加token到请求头，不是一个立即需要做的事情，可以靠后

    /**
     * PRE_DECORATION_FILTER 是Zuul默认的处理请求头的过滤器，我们放到这个之后执行
     * @return 顺序
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER +1 ;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Autowired
    private IntervalTokenHolder tokenHolder;

    @Override
    public Object run() throws ZuulException {


        RequestContext currentContext = RequestContext.getCurrentContext();

        //给zuul网关的请求头，添加内容,请求头的key时heima95,值是 api网关的token
        currentContext.addZuulRequestHeader("heima95",tokenHolder.getToken());

        return null;
    }
}
